package integral

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/integral"
	"private-domain-overseas-service/admin/business/api/internal/repository/user"
	"private-domain-overseas-service/pkg/constant"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzuser"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/samber/lo"
	"github.com/shopspring/decimal"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type IntegralGoodsOrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 积分消费订单列表
func NewIntegralGoodsOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *IntegralGoodsOrderListLogic {
	return &IntegralGoodsOrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *IntegralGoodsOrderListLogic) IntegralGoodsOrderList(req *types.IntegralGoodsOrderListReqeust) (resp *types.IntegralGoodsOrderListResponse, err error) {
	userDao := user.NewUsersDao(l.ctx, l.svcCtx)
	integralOrderDao := integral.NewIntegralOrderDao(l.ctx, l.svcCtx)

	// 定义百分之一初始值
	baiDecimal := decimal.NewFromInt32(100)

	//初始化积分兑换订单查询条件
	integralOrderConditions := make([]predicate.HzIntegralOrder, 0)
	orders, total, err := integralOrderDao.IntegralOrderByConditionPages(integralOrderConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerDataNotFoundError, fmt.Sprintf("分页查询积分兑换信息失败： %v", err))
	}

	//组装返回数据
	list := lo.Map(orders, func(item *ent.HzIntegralOrder, _ int) *types.IntegralGoodsOrder {
		userCond := make([]predicate.HzUser, 0)
		userCond = append(userCond, hzuser.IDEQ(int(item.OrderUserID)))
		userInfo, _ := userDao.UserByConditionsFirst(userCond)

		return &types.IntegralGoodsOrder{
			Id:              int64(item.ID),
			OrderNo:         item.OrderNo,
			CreatedAt:       time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			OrderStatus:     item.OrderStatus,
			GoodsId:         item.OrderGoodsID,
			GoodsInfo:       item.OrderGoodsInfo,
			GoodsImage:      fmt.Sprintf("%s%s", constant.IntegralGoodsImage, item.OrderGoodsImage),
			GoodsSmallImage: fmt.Sprintf("%s%s", constant.IntegralGoodsImage, item.OrderGoodsSmallImage),
			GoodsPrice:      decimal.NewFromInt(item.OrderPayAmount).Div(baiDecimal).StringFixed(2),
			GoodsSecret:     item.OrderGoodsSecret,
			UserPhone:       userInfo.UserPhone,
		}
	})

	//返回组装数据
	resp = &types.IntegralGoodsOrderListResponse{
		Page: &types.PageResponse{
			Current:         req.Current,
			PageSize:        req.PageSize,
			RequestPageSize: req.PageSize,
			Total:           int64(total),
		},
		List: list,
	}

	return resp, nil
}
